Zero-Shot Classification
One of CLIP’s most powerful capabilities is zero-shot classification: the ability to classify images into categories the model has never been explicitly trained on. This is achieved by comparing image embeddings with text embeddings of potential class labels.Core Concept
Instead of learning a fixed classifier head for specific categories, CLIP:- Encodes the image into an embedding vector
- Encodes candidate text labels (e.g., “a photo of a dog”) into embedding vectors
- Computes similarity scores between the image and each text embedding
- Selects the highest scoring label as the prediction
Key Insight: Classification becomes a similarity search problem in the joint embedding space, not a traditional softmax over learned weights.
How It Works
Step 1: Prepare Text Prompts
Convert class names into descriptive text prompts using templates:Why templates? Context matters! “a photo of a dog” provides more semantic information than just “dog”, leading to better embeddings.
Step 2: Build Zero-Shot Classifier Weights
Fromsrc/open_clip/zero_shot_classifier.py:21-68:
- Generate prompts for each class using multiple templates
- Encode all prompts to get text embeddings
- Average embeddings across templates for each class (ensemble)
- Normalize to unit length
- Transpose to shape
[embed_dim, num_classes]
Step 3: Classify Images
Fromsrc/open_clip_train/zero_shot.py:17-42:
- Encode image → normalized embedding vector
- Matrix multiply with classifier weights:
logits = image_features @ zeroshot_weights - Scale by 100 (temperature scaling)
- Argmax to get predicted class
Temperature Scaling and Similarity Computation
Cosine Similarity
Since both image and text embeddings are L2-normalized, their dot product equals cosine similarity:Temperature Scaling
The scaling factor (100.0 in the example) controls prediction confidence:- Higher temperature → sharper probability distribution, more confident predictions
- Lower temperature → softer distribution, less confident predictions
src/open_clip/model.py:274-298):
logit_scale is learned. At inference:
Softmax Probabilities
To get class probabilities:Real Example from Codebase
ImageNet Zero-Shot Evaluation
Fromsrc/open_clip_train/zero_shot.py:45-86:
- Model has never seen ImageNet classification task during training
- Build classifier from 1000 ImageNet class names using 7 prompt templates
- Evaluate on ImageNet validation set
- Achieve competitive accuracy without task-specific fine-tuning!
OpenAI’s ImageNet Templates
Used in the original CLIP paper:Practical Usage Example
Custom Classification
Classify an image into custom categories:Zero-Shot vs Fine-Tuning
Zero-Shot (No Fine-Tuning)
✅ Advantages:- Works on any categories without training data
- Instant deployment to new tasks
- No overfitting to specific datasets
- Leverages large-scale pretraining
- Lower accuracy than fine-tuned models on specific tasks
- Sensitive to prompt engineering
- May struggle with fine-grained distinctions
With Fine-Tuning
✅ Advantages:- Higher accuracy on target task
- Adapts to specific visual distributions
- Can learn task-specific features
- Requires labeled training data
- May lose zero-shot generalization
- Risk of overfitting
Advanced Techniques
Prompt Engineering
Better prompts → better performance:Ensemble Multiple Templates
Averaging embeddings across templates improves robustness (already done inbuild_zero_shot_classifier).
Hierarchical Classification
For fine-grained tasks, use two-stage classification:- Coarse categories: “bird”, “mammal”, “vehicle”
- Fine-grained: “golden retriever”, “labrador”, “poodle”
Performance Benchmarks
From the README, OpenCLIP models achieve strong zero-shot ImageNet accuracy:
Without any ImageNet-specific training!
Key Takeaways
- Zero-shot = Similarity search: Classification as nearest neighbor in embedding space
- Prompts matter: “a photo of a dog” > “dog”
- Template ensembling: Average across multiple prompts for robustness
- Temperature scaling: Controls prediction sharpness
- No training data needed: Instant deployment to new categories
- Trade-off: Convenience vs accuracy (compared to fine-tuning)
Reference Files
src/open_clip/zero_shot_classifier.py- Classifier building logicsrc/open_clip_train/zero_shot.py- Zero-shot evaluation during trainingsrc/open_clip/zero_shot_metadata.py- ImageNet classnames and templates
Related Concepts
CLIP Overview
Understanding the dual encoder architecture
Contrastive Learning
How CLIP learns aligned embeddings
Further Reading
- Original CLIP Paper: Learning Transferable Visual Models From Natural Language Supervision - Section 2.5 on zero-shot transfer
- WiSE-FT: Robust Fine-Tuning of Zero-shot Models - Combining zero-shot and fine-tuned models
- CLIP Benchmark: Standardized evaluation suite for 40+ datasets
